package com.cookapp.service;

import com.cookapp.common.exception.BusinessException;
import com.cookapp.common.enums.ResultCode;
import com.cookapp.common.utils.JwtUtils;
import com.cookapp.model.dto.SmsLoginDTO;
import com.cookapp.model.entity.User;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 手机号登录服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SmsLoginService {

    private final SmsService smsService;
    private final UserService userService;

    /**
     * 发送登录验证码
     */
    public void sendLoginCode(String phone) {
        smsService.sendSmsCode(phone);
    }

    /**
     * 手机号验证码登录
     */
    public String login(SmsLoginDTO smsLoginDTO) {
        // 验证短信验证码
        boolean verified = smsService.verifySmsCode(smsLoginDTO.getPhone(), smsLoginDTO.getCode());
        if (!verified) {
            throw new BusinessException(ResultCode.SMS_CODE_ERROR);
        }
        
        // 登录或注册用户
        User user = userService.loginByPhone(
                smsLoginDTO.getPhone(),
                smsLoginDTO.getNickname(),
                smsLoginDTO.getAvatar(),
                smsLoginDTO.getGender()
        );
        
        // 生成JWT token
        return JwtUtils.generateToken(user.getId());
    }
} 